package com.ktgj.customer.service.impl;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.hutool.core.img.ImgUtil;
import com.alibaba.fastjson.JSON;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.customer.domain.Bank;
import com.ktgj.customer.domain.Customer;
import com.ktgj.customer.domain.vo.BankCardVo;
import com.ktgj.customer.domain.vo.BankCareDto;
import com.ktgj.customer.domain.vo.BankInformation;
import com.ktgj.customer.domain.vo.BankVo;
import com.ktgj.customer.mapper.BankMapper;
import com.ktgj.customer.mapper.CustomerMapper;
import com.ktgj.customer.util.Clients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ktgj.customer.mapper.BankCardMapper;
import com.ktgj.customer.domain.BankCard;
import com.ktgj.customer.service.IBankCardService;

/**
 * 银行卡信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-09-01
 */
@Service
public class BankCardServiceImpl implements IBankCardService 
{
    @Autowired
    private BankCardMapper bankCardMapper;

    @Autowired
    private BankMapper bankMapper;

    @Autowired
    private CustomerMapper customerMapper;

    /**
     * 查询银行卡信息
     * 
     * @param bankCardId 银行卡信息ID
     * @return 银行卡信息
     */
    @Override
    public BankCard selectBankCardById(Long bankCardId)
    {
        return bankCardMapper.selectBankCardById(bankCardId);
    }

    /**
     * 查询银行卡信息列表
     * 
     * @param bankCard 银行卡信息
     * @return 银行卡信息
     */
    @Override
    public List<BankCard> selectBankCardList(BankCard bankCard)
    {
        return bankCardMapper.selectBankCardList(bankCard);
    }

    /**
     * 新增银行卡信息
     * 
     * @param bankCard 银行卡信息
     * @return 结果
     */
    @Override
    public int insertBankCard(BankCard bankCard)
    {
        return bankCardMapper.insertBankCard(bankCard);
    }

    /**
     * 修改银行卡信息
     * 
     * @param bankCard 银行卡信息
     * @return 结果
     */
    @Override
    public int updateBankCard(BankCard bankCard)
    {
        return bankCardMapper.updateBankCard(bankCard);
    }

    /**
     * 批量删除银行卡信息
     * 
     * @param bankCardIds 需要删除的银行卡信息ID
     * @return 结果
     */
    @Override
    public int deleteBankCardByIds(Long[] bankCardIds)
    {
        return bankCardMapper.deleteBankCardByIds(bankCardIds);
    }

    /**
     * 删除银行卡信息信息
     * 
     * @param bankCardId 银行卡信息ID
     * @return 结果
     */
    @Override
    public int deleteBankCardById(Long bankCardId)
    {
        return bankCardMapper.deleteBankCardById(bankCardId);
    }

//    String url = "http://172.16.7.51:9000/download";
    @Value("${bank-logo.url}")
    private String Url;
    /**
     * 当前用户已绑定的银行卡列表
     * @param memberId
     * @return
     */
    @Override
    public List<BankCardVo> selectBankCardByMemberIdList(Long memberId) throws Exception {
        List<BankCardVo> bankCardVoList = new CopyOnWriteArrayList<>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");

        List<BankCard> bankCardList=bankCardMapper.selectBankCardByMemberIdList(memberId);
        if (bankCardList == null || bankCardList.size() <= 0){
            throw new Exception("未查询到该会员的银行卡信息");
        }

        for (BankCard bankCard:bankCardList){
            if (bankCard.getIsDeletes().equals("false")){
                Bank bankName = bankMapper.selectBankByBankId(bankCard.getBankId());
                BankCardVo bankCardVo = new BankCardVo();
                bankCardVo.setBankCardId(bankCard.getBankCardId());
                bankCardVo.setBankName(bankName.getBankName());

                Bank bank = bankMapper.selectBankByBankId(bankCard.getBankId());
                bankCardVo.setLogoIconUrl(this.Url + bank.getLogoIconUrl());
                bankCardVo.setBackgroundColor(bank.getBackColor());
                bankCardVo.setExpired("true");

                if (bankCard.getCardType().equals("creditcard")){
//                bankCardVo.setCardType("信用卡");
                    bankCardVo.setCardType("creditcard");
                    String currentTime = sdf.format(new Date());
                    String creditCardTime = bankCard.getCreditCardTime();

                    long timeStart;
                    long timeEnd = 0l;
                    try {
                        timeStart = sdf.parse(currentTime).getTime();
                        if (creditCardTime != null){
                            timeEnd =sdf.parse(creditCardTime).getTime();
                        }
                    }catch (Exception e){
                        throw new Exception("日期转换错误");
                    }
                    long dayCount;
                    if (timeEnd != 0){
                        dayCount= (timeEnd-timeStart)/(24*3600*1000);
                    }
                    else {
                        dayCount= (timeStart)/(24*3600*1000);
                    }
                    long millisecond = timeEnd-timeStart;
                    if (dayCount > 0){
                        bankCardVo.setCreditCardTime(String.valueOf(dayCount));
                    }
                    else if (millisecond == 0){
                        bankCardVo.setCreditCardTime(String.valueOf(millisecond));
                    }
                    else if (millisecond < 0){
                        bankCardVo.setExpired("false");
                        bankCardVo.setCreditCardTime("-1");
                    }
                }
                else if (bankCard.getCardType().equals("debitcard")){
//                bankCardVo.setCardType("储蓄卡");
                    bankCardVo.setCardType("debitcard");
                }
//                bankCardVo.setCardNumber("**** **** **** "+bankCard.getCardNumber().substring(bankCard.getCardNumber().length()-4));
                bankCardVo.setCardNumber(bankCard.getCardNumber());
                bankCardVoList.add(bankCardVo);
            }
        }
        return bankCardVoList;
    }

    /**
     * 会员已绑定信用卡
     * */
    @Override
    public List<BankCardVo> creditCardList(Long customerId) {
        List<BankCard> bankCardList = bankCardMapper.creditCardList(customerId);
        if (bankCardList != null && bankCardList.size() > 0){
            List<BankCardVo> bankCardVoList = new ArrayList<>();
            for (BankCard bankCard : bankCardList) {
                BankCardVo bankCardVo = new BankCardVo();
                bankCardVo.setBankName(bankCard.getBankName());
                bankCardVo.setCreditCardTime(bankCard.getCreditCardTime());
                bankCardVo.setCardNumber(bankCard.getCardNumber());
                bankCardVo.setPhone(bankCard.getObligatePhone());
                bankCardVo.setCardType(bankCard.getCardType());
                bankCardVoList.add(bankCardVo);
            }
            return bankCardVoList;
        }
        else {
            return null;
        }
    }

    /**
     * 当前用户添加银行卡信息
     */
    @Override
    public int insertBankCardByMemberId(BankCard bankCard) {
        return bankCardMapper.insertBankCardByMemberId(bankCard);
    }

    /**
     * 绑定银行卡卡类型集合
     * */
    @Override
    public List<BankVo> selectBankVo() {
        List<Bank> bankList = bankMapper.selectbank();
        List<BankVo> bankVoList = new CopyOnWriteArrayList<>();
        for (Bank bank : bankList) {
            BankVo debitcard = new BankVo();
            debitcard.setBankCardType("debitcard");
            debitcard.setBankCardName("储蓄卡");
            debitcard.setBankName(bank.getBankName());
            debitcard.setLogoIconUrl(this.Url + bank.getLogoIconUrl());
            bankVoList.add(debitcard);

            BankVo creditcard = new BankVo();
            creditcard.setBankCardType("creditcard");
            creditcard.setBankCardName("信用卡");
            creditcard.setBankName(bank.getBankName());
            creditcard.setLogoIconUrl(this.Url + bank.getLogoIconUrl());
            bankVoList.add(creditcard);
        }
        return bankVoList;
    }

    /**
     * 根据银行代码查询银行信息
     * */
    @Override
    public Bank selectBankByBankCode(String cardNumber) throws Exception {
        Clients clients = new Clients();
        String post = clients.post(cardNumber);
        if (post != null){
            BankInformation bankInformation = JSON.parseObject(post, BankInformation.class);
            if (bankInformation != null && bankInformation.getStat().equals("ok")){
                Bank bank = bankMapper.selectBankByBankCode(bankInformation.getBank());
                if (bank != null){
                    bank.setLogoIconUrl("http://172.16.7.51:9000/download/appResource/" + bank.getLogoIconUrl());
                    if (bankInformation.getCardType().equals("DC"))
                        bank.setCardType("debitcard");
                    else if (bankInformation.getCardType().equals("CC"))
                        bank.setCardType("creditcard");
                    return bank;
                }
                else {
                    throw new Exception("没有该卡数据");
                }
            }
            else {
                throw new Exception("获取银行信息失败");
            }
        }
        else {
            throw new Exception("获取银行信息失败");
        }
    }

    /**
     * 根据id查询会员已绑定银行卡信息
     * */
    @Override
    public BankCard selectBankCardBytBankCardId(Long bankCardId) {
        BankCard bankCard = bankCardMapper.selectBankCardBytBankCardId(bankCardId);
        return bankCard;
    }

    /**
     * 会员已绑定银行卡列表（远程）
     * */
    @Override
    public List<BankCard> selectBankCardByMemberId(Long memberId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        List<BankCard> bankCards = new ArrayList<>();
        List<BankCard> bankCardList = bankCardMapper.selectBankCardByMemberId(memberId);
        if (bankCardList != null && bankCardList.size() > 0){
            for (BankCard bankCard : bankCardList) {
                if (bankCard.getIsDeletes().equals("false") && bankCard.getCardType().equals("creditcard")){
                    Date createTime;
                    Date date;
                    try {
                        createTime = format.parse(bankCard.getCreditCardTime());
                        date = format.parse(format.format(new Date()));
                    } catch (Exception e){
                        throw new Exception("时间转换错误");
                    }
                    int compareTo = createTime.compareTo(date);
                    if (compareTo == 1){
                        Bank bank = bankMapper.selectBankByBankId(bankCard.getBankId());
                        if (bank != null && bank.getLogoUrl() != null){
                            bankCard.bankLogoName = bank.getLogoUrl();
                            bankCards.add(bankCard);
                        }
                        else {
                            throw new Exception("未查询到银行logo信息");
                        }
                    }
                }
            }
            return bankCards;
        }
        else {
            return null;
        }
    }

    public String cardType(String cardType){
        switch (cardType){
            case "creditcard":
                cardType = "信用卡";
                break;
            case "debitcard":
                cardType = "借记卡";
                break;
        }
        return cardType;
    }

    public static int differentDays(Date date1,Date date2)
    {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2) //同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0) //闰年
                {
                    timeDistance += 366;
                }
                else //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
        }
        else //不同年
        {
            return day2-day1;
        }
    }

    public String documentsType(String documentsType){
        switch (documentsType){
            case "ID_CARD":
                documentsType = "身份证";
                break;
            case "MILITARY_ID":
                documentsType = "军人证";
                break;
            case "PASSPORT":
                documentsType = "护照";
                break;
            case "MTPFHKAMR":
                documentsType = "港澳居民来往内地通行证";
                break;
            case "MTPFTR":
                documentsType = "台湾居民来往大陆通行证";
                break;
            case "RPFHKMATR":
                documentsType = "港澳台居民居住证";
                break;
            case "PRICFF":
                documentsType = "外国人永久居留身份证";
                break;
            case "HKAMP":
                documentsType = "港澳通行证";
                break;
            case "ACCOUNT_BOOK":
                documentsType = "户口本";
                break;
            case "BIRTH_CERTIFICATE":
                documentsType = "出生证明";
                break;
            case "TAIWAN_PASS":
                documentsType = "台湾通行证";
                break;
        }
        return documentsType;
    }

    /**
     * 后端——查询银行卡
     * */
    @Override
    public List<BankCareDto> backSelectBankCard(Long memberId, String type) throws Exception {
        if (memberId != null && memberId != 0){
            List<BankCard> bankCardList;
            if (type != null && type.equals("hotel")){
                bankCardList = bankCardMapper.hotelSelectBankCard(memberId);
            }
            else {
                bankCardList = bankCardMapper.backSelectBankCard(memberId);
            }

            if (bankCardList != null && bankCardList.size() > 0){
                List<BankCareDto> bankCareDtoList = new ArrayList<>();
                for (BankCard bankCard : bankCardList) {
                    if (bankCard.getIsDeletes().equals("false")){
                        BankCareDto bankCareDto = new BankCareDto();
                        bankCareDto.setBankCardId(bankCard.getBankCardId());
                        bankCareDto.setBankName(bankCard.getBankName());
                        bankCareDto.setCardNumber(bankCard.getCardNumber());
                        bankCareDto.setCardType(cardType(bankCard.getCardType()));
                        if (bankCard.getCreateTime() != null){
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                            Date date = format.parse(format.format(new Date()));
                            Date time = format.parse(format.format(bankCard.getCreateTime()));
                            if (time.compareTo(date) > 0){
                                int days = differentDays(date, time);
                                if ((days / 30) >= 6){
                                    bankCareDto.setCreditCardTime(bankCard.getCreditCardTime());
                                }
                                else {
                                    bankCareDto.setCreditCardTime("不足6个月");
                                }
                            }
                            else {
                                bankCareDto.setCreditCardTime("已到期");
                            }
                        }
                        bankCareDto.setObligatePhone(bankCard.getObligatePhone());
                        bankCareDto.setCardholder(bankCard.getCardholder());
                        bankCareDto.setCommonCard(bankCard.getCommonCard());
                        Customer customer = customerMapper.selectCustomerById(memberId);
                        if (customer != null){
                            bankCareDto.setDocumentsType(documentsType(customer.getIdType()));
                            bankCareDto.setDocumentsPhone(customer.getCustCertificateNo());
                            bankCareDtoList.add(bankCareDto);
                        }
                        else {
                            throw new Exception("未查到数据");
                        }
                    }
                }
                return bankCareDtoList;
            }
            else {
                throw new Exception("未查到数据");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 后端——查询待修改银行卡
     * */
    @Override
    public BankCareDto backSelectBankCardById(Long bankCardId, Long memberId) throws Exception {
        if (bankCardId != null && bankCardId != 0){
            BankCard bankCard = bankCardMapper.backSelectBankCardById(bankCardId);
            if (bankCard != null){
                BankCareDto bankCareDto = new BankCareDto();
                bankCareDto.setBankCardId(bankCard.getBankCardId());
                bankCareDto.setBankName(bankCard.getBankName());
                bankCareDto.setCardNumber(bankCard.getCardNumber());
                bankCareDto.setCardType(cardType(bankCard.getCardType()));
                if (bankCard.getCreateTime() != null){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                    Date date = format.parse(format.format(new Date()));
                    Date time = format.parse(format.format(bankCard.getCreateTime()));
                    if (time.compareTo(date) > 0){
                        int days = differentDays(date, time);
                        if ((days / 30) >= 6){
                            bankCareDto.setCreditCardTime(bankCard.getCreditCardTime());
                        }
                        else {
                            bankCareDto.setCreditCardTime("不足6个月");
                        }
                    }
                    else {
                        bankCareDto.setCreditCardTime("已到期");
                    }
                }
                bankCareDto.setObligatePhone(bankCard.getObligatePhone());
                bankCareDto.setCardholder(bankCard.getCardholder());
                bankCareDto.setDocumentsType(bankCard.getIdType());
                bankCareDto.setDocumentsPhone(bankCard.getOwnerCdid());
                return bankCareDto;
            }
            else {
                throw new Exception("未查到数据");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 后端——新增银行卡
     * */
    @Override
    public BankCareDto backInsertBankCard(BankCareDto bankCareDto) throws Exception {
        if (bankCareDto != null && bankCareDto.getCustomerId() != null && bankCareDto.getCustomerId() != 0){
            Customer customer = customerMapper.selectCustomerById(bankCareDto.getCustomerId());
            if (customer != null){
                BankCard card = bankCardMapper.selectBackCardNum(customer.getCustomerId(), bankCareDto.getCardNumber());
                if (card != null){
                    bankCareDto.setBankCardId(card.getBankCardId());
                    bankCareDto.setBankName(card.getBankName());
                    bankCareDto.setCardNumber(card.getCardNumber());
                    bankCareDto.setCardType(card.getCardType());
                    bankCareDto.setCreditCardTime(card.getCreditCardTime());
                    bankCareDto.setCardholder(card.getCardholder());
                    bankCareDto.setObligatePhone(card.getObligatePhone());
                    bankCareDto.setCVV2(card.getCvv2());
                    bankCareDto.setCustomerId(customer.getCustomerId());
                    return bankCareDto;
                }
                else {
                    BankCard bankCard = new BankCard();
                    bankCard.setCardholder(customer.getCustomerName());
                    bankCard.setCardNumber(bankCareDto.getCardNumber());
//                    switch (bankCareDto.getCardType()){
//                        case "信用卡":
//                            bankCareDto.setCardType("creditcard");
//                            break;
//                        case "借记卡":
//                            bankCareDto.setCardType("debitcard");
//                            break;
//                    }
                    bankCard.setCardType(bankCareDto.getCardType());
                    bankCard.setObligatePhone(bankCareDto.getObligatePhone());
                    bankCard.setMemberId(bankCareDto.getCustomerId());
                    if (bankCareDto.getCreditCardTime() != null){
                        bankCard.setCreditCardTime(bankCareDto.getCreditCardTime());
                    }
                    if (bankCareDto.getCardNumber() != null){
                        String bank = backCard(bankCareDto.getCardNumber());
                        if (bank != null){
                            Bank byBankCode = bankMapper.selectBankByBankCode(bank);
                            bankCard.setBankName(byBankCode.getBankName());
                            bankCard.setBankId(byBankCode.getBankId());
                            bankCard.setCvv2(bankCareDto.getCVV2());
                            bankCard.setIsDeletes("false");
                            bankCard.setOwnerCdid(bankCareDto.getDocumentsPhone());
                            bankCard.setIdType(bankCareDto.getDocumentsType());
                            int i = bankCardMapper.backInsertBankCard(bankCard);
                            if (i > 0){
                                return bankCareDto;
                            }
                            else {
                                throw new Exception("新增失败");
                            }
                        }
                        else {
                            throw new Exception("未查到数据");
                        }
                    }
                    else {
                        throw new Exception("银行卡号不能为空");
                    }
                }
            }
            else {
                throw new Exception("未查到数据");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 卡号查银行代码
     * */
    @Override
    public String backCard(String cardNumber) throws Exception {
        Clients clients = new Clients();
        String post;
        try {
            post = clients.post(cardNumber);
        } catch (Exception e){
            throw new Exception("未查到银行卡对应银行信息");
        }
        String[] strs = post.split(",");
        String bank = null;
        for (String str : strs) {
            if (str.contains("bank")){
                bank = str;
                break;
            }
        }
        if (bank != null){
            int count = bank.indexOf(":");
            bank = bank.substring(count + 1).replace("\"", " ").trim();
            return bank;
        }
        else {
            return null;
        }
    }

    /**
     * 火车票银行卡支付查询银行卡信息
     * */
    @Override
    public BankCard backCardNum(String cardNumber) {
        BankCard bankCard = bankCardMapper.backCardNum(cardNumber);
        return bankCard;
    }

    /**
     * 后端——修改银行卡
     * */
    @Override
    public int backUpdateBankCard(BankCareDto bankCareDto) throws Exception {
        if (bankCareDto != null){
            BankCard bankCard = new BankCard();
            bankCard.setBankCardId(bankCareDto.getBankCardId());
            bankCard.setCardholder(bankCareDto.getCardholder());
            bankCard.setCardNumber(bankCareDto.getCardNumber());
            if (bankCareDto.getCardType() != null){
                /*switch (bankCareDto.getCardType()){
                    case "信用卡":
                        bankCareDto.setCardType("creditcard");
                        break;
                    case "借记卡":
                        bankCareDto.setCardType("debitcard");
                        break;
                }*/
                bankCard.setCardType(bankCareDto.getCardType());
            }
            else {
                throw new Exception("卡类型不能为空");
            }
            bankCard.setObligatePhone(bankCareDto.getObligatePhone());
            if (bankCareDto.getCardType().equals("debitcard")){
                bankCard.setCvv2(null);
                bankCard.setCreditCardTime(null);
            }
            else {
                bankCard.setCvv2(bankCareDto.getCVV2());
                bankCard.setCreditCardTime(bankCareDto.getCreditCardTime());
            }
            int i = bankCardMapper.backUpdateBankCard(bankCard);
            if (i > 0){
                return 1;
            }
            else {
                throw new Exception("修改失败");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 后端——删除银行卡
     * */
    @Override
    public int backDeleteBankCard(Long bankCardId) throws Exception {
        if (bankCardId != null && bankCardId != 0){
            int i = bankCardMapper.backDeleteBankCard(bankCardId);
            if (i > 0){
                return 1;
            }
            else {
                throw new Exception("删除失败");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    @Override
    public BankCard selectBackCardNum(Long memberId, String cardNumber) {
        BankCard bankCard = bankCardMapper.selectBackCardNum(memberId, cardNumber);
        return bankCard;
    }
}
